<template>
  <div class="vehicle-deployment" ref="vehicleDeployment">
    <div>
      <span>车辆投放</span>
      <el-button type="primary" :icon="FolderAdd" @click.stop="drawPoint"
        >添加</el-button
      >
    </div>
    <el-dialog v-model="dialogVisible" title="提示" width="400" draggable>
      <span class="dialog-content">
        <el-icon color="#E4A23A" size="20"><WarningFilled /></el-icon>
        该位置不在停车区域内,是否继续投放?
      </span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAddCar"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted, ref, createApp, watch } from "vue";
import { getAreas, getCars, deleteAreaById } from "@/api/api";
import { storeToRefs } from "pinia";
import mapboxgl from "mapbox-gl";
import AddCarPopup from "@/components/AddCarPopup.vue";
import { FolderAdd, WarningFilled } from "@element-plus/icons-vue";
import * as turf from "@turf/turf";
import { ElMessage, ElInput, ElButton } from "element-plus";
import { useMapStore, usePostStore } from "@/stores";
const mapStore = useMapStore();
const postStore = usePostStore();
const { updatePostCarResult } = postStore;
const { postCarResult } = storeToRefs(postStore);
const map = mapStore.Map;
const draw = mapStore.Draw;
const areaList = ref([]);
const vehicleDeployment = ref(null);
const dialogVisible = ref(false);
onMounted(async () => {
  vehicleDeployment.value.style.top = window.innerHeight * 0.07 + "px";
  const areas = await getAreas();
  await renderAreaList(areas);
  addAreaAndTextMarker();
});
//处理数据
const renderAreaList = async (areas) => {
  areas.forEach((area) => {
    const areaObj = {};
    areaObj.id = "area" + area.id;
    areaObj.name = area.name;
    areaObj.isEdit = ref(false);
    areaObj.count = ref(0);
    areaObj.coordinates = area.coordinates;
    areaList.value.push(areaObj);
  });
};
//添加图层
const addAreaAndTextMarker = () => {
  areaList.value.length &&
    areaList.value.forEach((areaObj) => {
      //如果有数据和图层则先移除
      removeLayerAndSource(areaObj.id);
      const polygon = turf.polygon(areaObj.coordinates);
      const center = turf.point(turf.centroid(polygon).geometry.coordinates, {
        name: areaObj.name,
      });
      //添加多边形
      map.addSource(areaObj.id + "source-fill", {
        type: "geojson",
        data: polygon,
      });
      map.addLayer({
        id: areaObj.id + "layer-fill",
        source: areaObj.id + "source-fill",
        type: "fill",
        paint: {
          "fill-color": "#ABA7A5",
          "fill-opacity": 0.6,
        },
      });
      //添加文字标注
      map.addSource(areaObj.id + "source-text", {
        type: "geojson",
        data: center,
      });
      map.addLayer({
        id: areaObj.id + "layer-text",
        source: areaObj.id + "source-text",
        type: "symbol",
        layout: {
          "text-field": ["get", "name"],
        },
        paint: {
          // 修改文字的颜色
          "text-color": "white",
        },
      });
    });
};
//移除图层和source
const removeLayerAndSource = (id) => {
  map.getLayer(id + "layer-fill") && map.removeLayer(id + "layer-fill");
  map.getSource(id + "source-fill") && map.removeSource(id + "source-fill");
  map.getLayer(id + "layer-text") && map.removeLayer(id + "layer-text");
  map.getSource(id + "source-text") && map.removeSource(id + "source-text");
};
let currentCoordinates;
//绘制点数据
const drawPoint = () => {
  //先添加
  map.addControl(draw, "top-left");
  //弹出一个消息提示
  ElMessage("请绘制投放车辆的位置");
  map.off("draw.create");
  draw.changeMode("draw_point");
  map.on("draw.create", (e) => {
    currentCoordinates = e.features[0].geometry.coordinates;
    const point = turf.point(currentCoordinates);
    let flag = false;
    for (let i = 0; i < areaList.value.length; i++) {
      const polygon = turf.polygon(areaList.value[i].coordinates);
      flag = turf.booleanPointInPolygon(point, polygon);
      if (flag) {
        break;
      }
    }
    if (!flag) {
      dialogVisible.value = true;
    } else {
      addCar();
    }
  });
};
const addCar = () => {
  const div = document.createElement("div");
  const addCarApp = createApp(AddCarPopup, { currentCoordinates });
  addCarApp.use(ElButton).use(ElInput).mount(div);
  const popup = new mapboxgl.Popup({
    closeOnClick: false,
  })
    .setLngLat(currentCoordinates)
    .setDOMContent(div)
    .addTo(map);
  //监听postCarResult的改变
  const unwatch = watch(postCarResult, () => {
    popup.remove();
    unwatch();
    draw.deleteAll();
    map.removeControl(draw);
    updatePostCarResult(false);
  });
  popup.on("close", () => {
    unwatch();
    draw.deleteAll();
    map.removeControl(draw);
  });
};

//当车的位置不在区域范围内时确定添加车辆
const confirmAddCar = () => {
  dialogVisible.value = false;
  addCar();
};
</script>

<style scoped>
.vehicle-deployment {
  width: 200px;
  position: absolute;
  right: 40px;
  z-index: 10;
  background-color: white;
}
.vehicle-deployment div {
  margin: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.vehicle-deployment div span {
  font-weight: 600;
  font-size: 14px;
}
.vehicle-deployment .dialog-content {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  gap: 10px;
  font-weight: 400;
}
.vehicle-deployment .dialog-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 10px;
}
</style>
